﻿using System;
using System.Threading;

namespace HslCommunication.Core
{
	/// <summary>
	/// 一个用于高性能，乐观并发模型控制操作的类，允许一个方法(隔离方法)的安全单次执行
	/// </summary>
	// Token: 0x0200011C RID: 284
	public sealed class HslAsyncCoordinator
	{
		/// <summary>
		/// 实例化一个对象，需要传入隔离执行的方法
		/// </summary>
		/// <param name="operater">隔离执行的方法</param>
		// Token: 0x06001888 RID: 6280 RVA: 0x0007CF5B File Offset: 0x0007B15B
		public HslAsyncCoordinator(Action operater)
		{
			this.action = operater;
		}

		/// <summary>
		/// 启动线程池执行隔离方法
		/// </summary>
		// Token: 0x06001889 RID: 6281 RVA: 0x0007CF84 File Offset: 0x0007B184
		public void StartOperaterInfomation()
		{
			Interlocked.Increment(ref this.Target);
			bool flag = Interlocked.CompareExchange(ref this.OperaterStatus, 1, 0) == 0;
			if (flag)
			{
				ThreadPool.QueueUserWorkItem(new WaitCallback(this.ThreadPoolOperater), null);
			}
		}

		// Token: 0x0600188A RID: 6282 RVA: 0x0007CFC8 File Offset: 0x0007B1C8
		private void ThreadPoolOperater(object obj)
		{
			long num = this.Target;
			long num2 = 0L;
			long num3;
			do
			{
				num3 = num;
				Action action = this.action;
				if (action != null)
				{
					action();
				}
				num = Interlocked.CompareExchange(ref this.Target, num2, num3);
			}
			while (num3 != num);
			Interlocked.Exchange(ref this.OperaterStatus, 0);
			bool flag = this.Target != num2;
			if (flag)
			{
				this.StartOperaterInfomation();
			}
		}

		/// <inheritdoc />
		// Token: 0x0600188B RID: 6283 RVA: 0x0007D035 File Offset: 0x0007B235
		public override string ToString()
		{
			return "HslAsyncCoordinator";
		}

		// Token: 0x04000567 RID: 1383
		private Action action = null;

		// Token: 0x04000568 RID: 1384
		private int OperaterStatus = 0;

		// Token: 0x04000569 RID: 1385
		private long Target = 0L;
	}
}
